import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import './App.scss'
import { useAppDispatch } from './store'
import { get_user_info_async } from './store/slice/user/request'
import eventBus from './util/event'
import { notification } from 'antd'
import { LogoutPost } from './util/request'
import useRenderCount from './hooks/useRenderCount'
import WrapedRoutes from './router/WrapedRoutes'

// 处理错误的函数
const openNotification = (msg: string) => {
  notification.error({
    message: '错误',
    description: `错误信息：${msg}`
  })
}

// APP组件
function App() {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  // 统计APP渲染次数
  useRenderCount('App')

  // 获取用户信息
  useEffect(() => {
    dispatch(get_user_info_async())
    // if (pathKey !== 'login') {
    //   // 获取用户信息\
    //   dispatch(get_menu_async())
    // }

    // 未登录
    eventBus.on('global_not_login', function (msg) {
      navigate('/login')
    })

    // 没有权限
    eventBus.on('global_error_auth', function (msg) {
      openNotification(msg)

      LogoutPost().then(() => {
        navigate('/login')
      })
    })

    // 业务错误
    eventBus.on('global_error_tips', function (msg) {
      openNotification(msg)
    })
  }, [])

  return (
    <>
      <WrapedRoutes></WrapedRoutes>
    </>
  )
}

export default App
